package com.east.config.handler;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.stream.StreamUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.east.entity.User;
import com.east.entity.UserRole;
import com.east.mapper.UserMapper;
import com.east.result.Result;
import com.east.service.UserRoleService;
import com.east.service.UserService;
import com.east.utils.Constants;
import com.east.utils.JWTUtils;
import com.east.utils.ResponseUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 登陆成功处理器
 */
@Component
public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private UserRoleService userRoleService;
    @Resource
    private UserMapper userMapper;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        // 1. 获取登陆的用户信息
        User user = (User) authentication.getPrincipal();
        // 1.1 给用户分配角色
        List<String> roleByUserId = userRoleService.getRoleByUserId(user.getId());
        user.setRoleList(roleByUserId);
        // 1.2 设置用户的菜单
        User info = userMapper.info(user.getId().longValue());
        user.setMenuList(info.getMenuList());
        // 1.3 设置用户的按钮
        user.setButtonList(info.getButtonList());
        // 2. 生成用户的jwt
        String jsonStr = JSONUtil.toJsonStr(user);
        String jwt = JWTUtils.createJWT(jsonStr);
        // 3. 如果传入remremberme参数，将redis中的jwt有效期设为30天
        String rememberMe = request.getParameter(Constants.REMEMBERME_NAME);
        if (StrUtil.isNotBlank(rememberMe) && BooleanUtil.toBoolean(rememberMe)) {
            stringRedisTemplate.opsForValue().set(Constants.REDIS_JWT_KEY + user.getId().toString(), jwt,
                    Constants.DEFAULT_EXPIRE_TIME, TimeUnit.DAYS);
        } else {
            // 3.1 将jwt写入redis,用户的id作为key，有效期为30分钟
            stringRedisTemplate.opsForValue().set(Constants.REDIS_JWT_KEY + user.getId().toString(), jwt,
                    Constants.DEFAULT_EXPIRE_TIME, TimeUnit.MINUTES);
        }
        HashMap<Object, Object> map = new HashMap<>();
        // 5. 将jwt封装进map,返回给前端
        map.put(Constants.TOKEN_NAME, jwt);
        String resJson = JSONUtil.toJsonStr(Result.OK(map));
        System.out.println("登陆成功");
        ResponseUtils.write(response, resJson);
    }
}
